<!--
  * 用户表
  *
  * @Author:    zhoujk
  * @Date:      2025-01-23 04:08:29

-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="输入查询" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.keywords" placeholder="员工姓名/登录账号/手机号" />
      </a-form-item>
      <a-form-item label="员工角色" class="smart-query-form-item">
        <RolePageSelect ref="roleSelect" placeholder="请选择" width="200px" v-model:value="queryForm.roleId" :leaveFlag="false" :multiple="false" />
      </a-form-item>
      <a-form-item label="所属部门" class="smart-query-form-item">
        <DepartTreeSelect width="200px" v-model:value="queryForm.oDepartId" placeholder="请选择" />
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="onSearch">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="showForm" type="primary" class="smart-margin-left20">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <!-- <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.SYSTEM.USER" :refresh="queryData" /> -->
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :loading="tableLoading" :pagination="false">
      <template #bodyCell="{ text, record, column }">
        <!-- 有图片预览时 注释解开并把下面的'picture'修改成自己的图片字段名即可 -->
        <!-- <template v-if="column.dataIndex === 'picture'">
            <FilePreview :fileList="text" type="picture" />
          </template> -->

        <!-- 使用字典时 注释解开并把下面的'data-dictionaries'修改成自己的字典字段名即可 有多个字典字段就复制多份同理修改 不然不显示字典 -->
        <!-- 方便修改tag的颜色 orange green purple success processing error default warning -->
        <!-- <template v-if="column.dataIndex === 'data-dictionaries'">
          <a-tag color="cyan">
            {{ text && text.length > 0 ? text.map((e) => e.valueName).join(',') : '暂无' }}
          </a-tag>
        </template> -->

        <template v-if="column.dataIndex === 'sex'">
          <span>{{ $smartEnumPlugin.getDescByValue('ZZB_SEX_ENUM', text) }}</span>
        </template>

        <template v-if="column.dataIndex === 'roles'">
          <div v-if="text && text.length" class="tag-container">
            <a-tag v-for="(item, index) in text" :key="item.id" :color="userRoleColorArray[index]">
              {{ item.name }}
            </a-tag>
          </div>
          <span v-else>-</span>
        </template>

        <template v-if="column.dataIndex === 'status'">
          <a-switch
            :checked="text === ZZB_ENABLE_STATUS_ENUM.ENABLE_STATUS.value"
            @change="(checked) => handleStatusChangeConfirm(checked, record)"
            :loading="record.statusLoading"
          />
        </template>

        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="showForm(record)" type="link">编辑</a-button>
            <a-button @click="confirmBatchDelete(record)" danger type="link">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNo"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>

    <UsersForm ref="formRef" @reloadList="queryData" />
  </a-card>
</template>
<script setup>
  import { reactive, ref, onMounted, createVNode } from 'vue'
  import { message, Modal } from 'ant-design-vue'
  import { SmartLoading } from '/src/components/framework/smart-loading'
  import { userApi } from '/src/api/system/b-merchant/user-api'
  import { PAGE_SIZE_OPTIONS } from '/src/constants/common-const'
  import { smartSentry } from '/src/lib/smart-sentry'
  import TableOperator from '/src/components/support/table-operator/index.vue'
  import UsersForm from './components/user-form.vue'
  import { ZZB_ENABLE_STATUS_ENUM } from '/src/constants/system/system-const.js'
  import DepartTreeSelect from '/src/components/system/b-merchant/depart-tree-select/index.vue'
  import RolePageSelect from '/src/components/system/b-merchant/role-page-select/index.vue'
  import { TABLE_ID_CONST } from '/src/constants/support/table-id-const.js'
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
  import { loginApi } from '/src/api/system/b-auth/login-api.js'

  // ---------------------------- 表格列 ----------------------------
  const userRoleColorArray = ['red', 'blue', 'orange', 'green']

  const columns = ref([
    {
      title: '员工姓名',
      dataIndex: 'name',
      width: 100,
      ellipsis: true,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      width: 50,
      ellipsis: true,
    },
    {
      title: '所属部门',
      dataIndex: 'oDepartName',
      width: 200,
      ellipsis: true,
    },
    {
      title: '当前角色',
      dataIndex: 'roles',
      width: 200,
      ellipsis: true,
    },
    {
      title: '登录账号',
      dataIndex: 'no',
      width: 100,
      ellipsis: true,
    },
    {
      title: '手机',
      dataIndex: 'phone',
      width: 100,
      ellipsis: true,
    },
    {
      title: '启用',
      dataIndex: 'status',
      width: 60,
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 200,
    },
  ])

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    nameLeftLike: undefined, // 输入查询
    roleId: undefined, // 员工角色
    oDepartId: undefined, // 所属部门
    showRoleFlag: true, // 所属部门
    ignoreFixedFlag: true, // 显示固定角色用户
    pageNo: 1,
    pageSize: 10,
    keywords: undefined,
  }
  // 查询表单form
  const queryForm = reactive({ ...queryFormState })
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize
    Object.assign(queryForm, queryFormState)
    queryForm.pageSize = pageSize
    queryData()
  }

  // 搜索
  function onSearch() {
    queryForm.pageNo = 1
    queryData()
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true
    try {
      let queryResult = await userApi.page(queryForm)
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  onMounted(queryData)

  // ---------------------------- 添加/修改 ----------------------------
  const formRef = ref()

  function showForm(data) {
    formRef.value.show(data)
  }

  // ---------------------------- 状态修改 ----------------------------
  const handleStatusChangeConfirm = async (checked, record) => {
    Modal.confirm({
      title: '状态变更',
      icon: createVNode(ExclamationCircleOutlined),
      content: `确认修改"${record.name}"状态为${checked ? '启用' : '禁用'}`,
      okText: '确认',
      cancelText: '取消',
      async onOk() {
        const res = await loginApi.getLoginInfo()
        if (record.no === res.data?.no) {
          Modal.confirm({
            title: '状态变更',
            icon: createVNode(ExclamationCircleOutlined),
            content: `不可随意禁用会影响账号的无法使用，如果禁用了请联系管理员`,
            okText: '确认',
            cancelText: '取消',
            onOk() {
              handleStatusChange(checked, record)
            },
          })
        } else {
          handleStatusChange(checked, record)
        }
      },
    })
  }

  const handleStatusChange = async (checked, record) => {
    /// 保存原始值用于错误回滚
    const originalStatus = record.status
    // 将布尔值转换为 0/1
    const targetStatus = checked ? ZZB_ENABLE_STATUS_ENUM.ENABLE_STATUS.value : ZZB_ENABLE_STATUS_ENUM.DISABLE_STATUS.value
    try {
      record.statusLoading = true

      const response = await userApi.updateStatus({ id: record.id, status: targetStatus })
      if (response && response.code === 200) {
        // 更新本地状态
        record.status = targetStatus
        message.success('状态更新成功')
      } else {
        message.error('状态更新失败')
        // 如果更新失败，恢复原状态
        record.status = originalStatus
      }
    } catch (e) {
      smartSentry.captureError(e)
      record.status = originalStatus
    } finally {
      record.statusLoading = false
    }
  }

  // ---------------------------- 批量删除 ----------------------------

  // 选择表格行
  const selectedRowKeyList = ref([])

  function onSelectChange(selectedRowKeys) {
    selectedRowKeyList.value = selectedRowKeys
  }

  // 删除
  async function confirmBatchDelete(record) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除该用户吗?',
      okText: '删除',
      okType: 'danger',
      async onOk() {
        const res = await loginApi.getLoginInfo()
        if (record.no === res.data?.no) {
          Modal.confirm({
            title: '提示',
            content: '不可随意删除会影响账号的无法使用，如果禁用了请联系管理员',
            okText: '删除',
            okType: 'danger',
            onOk() {
              requestBatchDelete(record)
            },
          })
        } else {
          requestBatchDelete(record)
        }
      },
      cancelText: '取消',
      onCancel() {},
    })
  }

  //请求删除
  async function requestBatchDelete(record) {
    try {
      SmartLoading.show()
      await userApi.delete({ id: record.id })
      message.success('删除成功')
      queryData()
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      SmartLoading.hide()
    }
  }
</script>
<style>
  .tag-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
</style>
